package com.lt.hospital.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.lt.cmn.client.DictFeignClient;
import com.lt.hospital.model.hosp.Hospital;
import com.lt.hospital.repository.HospitalRepository;
import com.lt.hospital.service.HospitalService;
import com.lt.hospital.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private DictFeignClient dictFeignClient;

    /**
     * 提交医院信息
     * @param stringObjectMap
     */
    @Override
    public void save(Map<String, Object> stringObjectMap) {
        //把集合转为对象指的就是hospital
            //首先将map对象转换为字符串
            String jsonString = JSONObject.toJSONString(stringObjectMap);
            //再将字符串转换为对象
            Hospital hospital = JSONObject.parseObject(jsonString, Hospital.class);

        //我们需要判断传来的数据是否已经存在

            //从数据库查询
            String hoscode = hospital.getHoscode();
            //调用hospitalRepository方法
            Hospital hospitalExist = hospitalRepository.getHospitalByHoscode(hoscode);

        //如果存在，那么我们更新操作
            if(null != hospitalExist){
                hospital.setStatus(hospitalExist.getStatus());//获取医院是否上线状态
                hospital.setCreateTime(hospitalExist.getCreateTime());//医院创建时间就是当初时间
                hospital.setUpdateTime(new Date());//修改时间就是现在
                hospital.setIsDeleted(0);//逻辑删除值为0
                hospitalRepository.save(hospital);//mongodb内部的保存提交方法
            }else{
                //如果不存在，添加操作
                hospital.setStatus(0);
                hospital.setCreateTime(new Date());
                hospital.setUpdateTime(new Date());
                hospital.setIsDeleted(0);
                hospitalRepository.save(hospital);
            }


    }

    @Override
    public Hospital getHospitalByHoscode(String hoscode) {
        //getHospitalByHoscode这个方法在hospitalRepository上面已经写好了，这个名字与上面的一致，但是不一样
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        return hospital;
    }

    /**
     * 条件分页查询
     * @param page
     * @param limit
     * @param hospitalQueryVo
     * @return
     */
    @Override
    public Page<Hospital> findPageHospital(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        //创建Pageable对象，这里page和和mysql里面不一样，下标从0开始，所以设置时候要将当前页减去1
        Pageable pageable = PageRequest.of(page-1,limit);

        //创建Hospital对象
        Hospital hospital = new Hospital();
        //将hospitalQueryVo对象转换为department对象
        BeanUtils.copyProperties(hospitalQueryVo, hospital);

        //创建Example对象，这是mongo里面的写法
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符,串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        //创建实例
        Example<Hospital> example = Example.of(hospital, matcher);

        Page<Hospital> all = hospitalRepository.findAll(example, pageable);

        //获取到所有的hospital对象

        all.getContent().stream().forEach(item ->{
            this.setHospitalHosType(item);
        });

        return all;
    }



    private Hospital setHospitalHosType(Hospital hospital) {
        //查询医院等级类型，mongodb当中yygh_hosp的hospital表中hostype字段就代表的是医院类型，在数据字典的dict_code能找到
        String hostype = dictFeignClient.getName("Hostype", hospital.getHostype());
        //查询省市地区
        String province = dictFeignClient.getName(hospital.getProvinceCode());
        String city = dictFeignClient.getName(hospital.getCityCode());
        String district = dictFeignClient.getName(hospital.getDistrictCode());
        //getParam()是hospital类中自己加的字段，不存入数据库
        hospital.getParam().put("hostype",hostype);
        hospital.getParam().put("fullAddress",province+city+district);
        return hospital;
    }

    /**
     * 医院状态设置
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(String id, Integer status) {
        Hospital hospital = hospitalRepository.findById(id).get();
        hospital.setStatus(status);
        hospital.setUpdateTime(new Date());
        hospitalRepository.save(hospital);
    }

    @Override
    public Map<String, Object> showHospitalDetail(String id) {

        Map<String, Object> result = new HashMap<>();
        //将医院信息进行封装
        Hospital hospital = this.setHospitalHosType(hospitalRepository.findById(id).get());
        //医院的基本信息，包括医院等级
        result.put("hospital", hospital);
        //医院预约信息
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回，之后设置医院的预约信息为空，因为已经被预约了
        hospital.setBookingRule(null);

        return result;

    }

    /**
     * 根据医院名称查询医院
     * @param hosname
     * @return
     */
    @Override
    public List<Hospital> getHospitalByHosname(String hosname) {
        List<Hospital> hospitalList=hospitalRepository.getHospitalByHosnameLike(hosname);
        return hospitalList;
    }

    /**
     * 用户界面需要获取到的医院预约详情
     * @param hoscode
     * @return
     */
    @Override
    public Map<String, Object> item(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        //医院详情
        Hospital hospital = this.setHospitalHosType(this.getHospitalByHoscode(hoscode));
        result.put("hospital", hospital);
        //预约规则
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }
}
